package utils

import (
	"io/fs"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
)

func PathExists(filename string) bool {
	_, err := os.Stat(filename)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func ListFiles(path, filePattern string, withDir bool) ([]fs.FileInfo, error) {
	if runtime.GOOS != "windows" {
		if path[0] != '/' {
			path = ToAbsolutePath(path)
		}
	} else {
		if path[0] != '/' && path[0] != '\\' && (len(path) < 2 || path[1] != ':') {
			path = ToAbsolutePath(path)
		}
	}

	dirEntries, err := os.ReadDir(path)
	if err != nil {
		return nil, err
	}

	var reg *regexp.Regexp
	if filePattern != "" {
		reg, err = regexp.Compile(filePattern)
		if err != nil {
			return nil, err
		}
	}

	files := make([]fs.FileInfo, 0)
	for _, oneEntry := range dirEntries {
		if withDir || !oneEntry.IsDir() {
			fileInfo, _ := oneEntry.Info()
			add := true
			if !oneEntry.IsDir() && reg != nil {
				add = reg.MatchString(fileInfo.Name())
			}
			if add {
				files = append(files, fileInfo)
			}
		}
	}

	return files, nil
}

func ToAbsolutePath(path string) string {
	str, _ := os.Getwd()
	if strings.HasPrefix(path, "../") {
		str = filepath.Dir(str)
		path = path[3:]
	} else {
		path = strings.TrimPrefix(path, "./")
	}
	return str + "/" + path
}

func IsVideoFile(filename string) bool {
	if strings.HasSuffix(filename, ".mp4") ||
		strings.HasSuffix(filename, ".mpg") ||
		strings.HasSuffix(filename, ".mpeg") ||
		strings.HasSuffix(filename, ".avi") ||
		strings.HasSuffix(filename, ".flv") {
		return true
	}
	return false
}

func IsAudioFile(filename string) bool {
	if strings.HasSuffix(filename, ".mp3") ||
		strings.HasSuffix(filename, ".ogg") ||
		strings.HasSuffix(filename, ".wav") ||
		strings.HasSuffix(filename, ".wma") {
		return true
	}
	return false
}

func IsTextFile(filename string) bool {
	if strings.HasSuffix(filename, ".txt") ||
		strings.HasSuffix(filename, ".log") ||
		strings.HasSuffix(filename, ".ini") ||
		strings.HasSuffix(filename, ".conf") {
		return true
	}
	return false
}
